<template>
  <div class="knowledge-base">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="app.appConfig?.basic?.appName"
      left-text=""
      right-text=""
      @click-left="openHistory"
      @click-right="closeChat"
    >
      <template #left>
        <van-icon name="bars" size="24" />
      </template>
      <template #right>
        <van-icon name="close" size="24" />
      </template>
    </van-nav-bar>

    <!-- 聊天内容区域 -->
    <div ref="messagesContainer" class="chat-content">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.role]"
      >
        <div v-if="message.role === 'assistant'" class="message-avatar">
          {{ app.nickName }}
        </div>
        <div
          v-if="
            message.role === 'assistant' && !message.content && !message.think
          "
          class="message-bubble"
        >
          <van-loading type="spinner" />
        </div>
        <div v-else-if="message.role === 'user'" class="message-bubble">
          <span>{{ message.content }}</span>
        </div>
        <AiMessage v-else :message="message" @restart="restart" />
      </div>
    </div>

    <!-- 输入框和发送按钮 -->
    <div class="input-area">
      <van-field
        v-model="inputMessage"
        type="textarea"
        placeholder="请输入问题"
        rows="1"
        :border="false"
        autosize
        :disabled="isLoading"
        @keydown.enter="keyDown"
      />
      <van-button
        class="send-button"
        type="primary"
        v-if="!isLoading"
        @click="sendMessage"
      >
        <img class="send-icon" :src="sendIcon" />
      </van-button>
      <van-button
        v-else
        class="send-button"
        type="danger"
        icon="stop"
        @click="stopChat"
      />
    </div>

    <van-popup
      v-model:show="showLeft"
      position="left"
      :style="{ width: '60%', height: '100%' }"
      @open="openLeft"
    >
      <HistoryList
        ref="historyListRef"
        :app-id="appId"
        @add="add"
        @click-item="clickHistoryItem"
      />
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import sendIcon from "@/assets/send.svg";
import HistoryList from "./HistoryList.vue";
import { AppApi } from "@/api/index.ts";
import AiMessage from "@/components/AiMessage.vue";
const router = useRouter();
//应用ID
const appId: any = localStorage.getItem("state") || "";
//用户名
const username: any = localStorage.getItem("user_name") || "";

const inputMessage = ref("");
const messages = ref<any[]>([]);
const isLoading = ref(false);
const messagesContainer = ref<any>(null);
const app = ref<any>({});
const showLeft = ref(false);
const contextId = ref<string | null>(null);
const chatId = ref<number | null>(null);
const testApiFlag = import.meta.env.VITE_API_TEST_FLAG.toLowerCase() === "true";
const historyListRef = ref<any>(null);
AppApi.login(username)
  .then((_: any) => {
    globalThis.console.log("login success");
    AppApi.getAppInfo(appId, "1").then((data: any) => {
      app.value = data;
      app.value.nickName = data?.appConfig?.basic?.appName?.substring(0, 1);
      // 初始化欢迎消息
      messages.value.push({
        role: "assistant",
        content: app.value.appConfig?.prologue?.prologue,
      });
    });
  })
  .catch((error: any) => {
    globalThis.console.log(error);
    router.replace({ name: "404" });
  });
const keyDown = (e: any) => {
  if (e.ctrlKey && e.keyCode == 13) {
    sendMessage();
  }
};

function parseMessage(output: string, message: any) {
  const thinkStartPos = output.indexOf("<think>");
  const thinkEndPos = output.indexOf("</think>");
  if (thinkStartPos >= 0 && thinkEndPos >= 0) {
    message.think = output.substring(thinkStartPos + 7, thinkEndPos);
    message.thinking = false;
    message.content = output.substring(thinkEndPos + 8);
  } else if (thinkStartPos >= 0) {
    message.think = output.substring(thinkStartPos + 7);
    message.thinking = true;
    message.content = "";
  } else {
    message.content = output;
  }
}
function parseContext(output: string) {
  const thinkStartPos = output.indexOf("<think>");
  const thinkEndPos = output.indexOf("</think>");
  let msg = {
    think: "",
    thinking: false,
    content: "",
  };
  if (thinkStartPos >= 0 && thinkEndPos >= 0) {
    msg.think = output.substring(thinkStartPos + 7, thinkEndPos);
    msg.thinking = false;
    msg.content = output.substring(thinkEndPos + 8);
    return msg;
  } else if (thinkStartPos >= 0) {
    msg.think = output.substring(thinkStartPos + 7);
    msg.thinking = true;
    msg.content = "";
    return msg;
  } else {
    msg.content = output;
    return msg;
  }
}

const onMessage = async (data: any) => {
  if (data.code === 0) {
    // 更新最后一条消息（助手消息）
    const output = data.result.output;
    if (!output) {
      return;
    }
    const message = messages.value[messages.value.length - 1];
    parseMessage(output, message);
    contextId.value = data.result.contextId;
    chatId.value = data.result.id;
    message.contextId = data.result.contextId;
    message.chatId = data.result.id;
    message.finished = data.result.finishState === "stop";
    message.input = data.result.input;
    if (data.result.finishState === "stop") {
      message.thinking = false;
      isLoading.value = false;
    }
    await scrollToBottom();
  } else {
    const message = messages.value[messages.value.length - 1];
    message.content = "抱歉，发送消息时出现错误: " + data.message;
  }
};
// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;

  // 添加用户消息
  messages.value.push({
    role: "user",
    content: message,
  });

  const userMessage = message;
  inputMessage.value = "";
  isLoading.value = true;

  await scrollToBottom();

  try {
    // 添加助手消息占位
    messages.value.push({
      role: "assistant",
      content: "",
      think: "",
      thinking: true,
      finished: false,
    });
    await scrollToBottom();
    await AppApi.chat(
      appId,
      {
        text: userMessage,
        contextId: contextId.value,
        chatId: chatId.value,
        test: testApiFlag,
      },
      onMessage
    );
  } catch (error: any) {
    globalThis.console.error("Error sending message:", error);
    messages.value.push({
      role: "assistant",
      content: "抱歉，发送消息时出现错误: " + error.message,
    });
  } finally {
    isLoading.value = false;
    await scrollToBottom();
  }
};
onMounted(() => {});

const openLeft = async () => {
  if (historyListRef.value) {
    await historyListRef.value.loadData();
  }
};

const add = async () => {
  showLeft.value = false;
  messages.value = [];
  chatId.value = null;
  contextId.value = null;
  // 初始化欢迎消息
  messages.value.push({
    role: "assistant",
    content: app.value.appConfig?.prologue?.prologue,
  });
};

const clickHistoryItem = async (item: any) => {
  showLeft.value = false;
  messages.value = [];
  chatId.value = item.chatId;
  contextId.value = item.id;
  // messages.value.push({
  //   role: "user",
  //   content: item.title,
  // });
  AppApi.getChatHistoryDetail(item.id).then((res: any) => {
    res.forEach(async (value: any) => {
      let msg = {
        role: "assistant",
        thinking: false,
        finished: true,
        input: "",
        contextId: "",
        chatId: "",
        content: "",
        think: "",
      };
      msg.input = value.input;
      msg.contextId = item.id;
      msg.chatId = value.outputs[0].id;
      let result: any = await parseContext(value.outputs[0].output);
      msg.think = result.think;
      msg.thinking = result.thinking;
      msg.finished = true;
      msg.content = result.content;
      messages.value.push({
        role: "user",
        content: value.input,
      });
      messages.value.push(msg);
    });
  });
};

const restart = async (message: any) => {
  isLoading.value = true;
  messages.value.push({
    role: "assistant",
    content: "",
    think: "",
    thinking: true,
    finished: false,
  });
  await AppApi.restart(
    appId,
    message.contextId,
    {
      text: message.input,
      contextId: message.contextId,
      chatId: message.chatId,
      test: testApiFlag,
    },
    onMessage
  );
};

// 滚动到最新消息
const scrollToBottom = async () => {
  await nextTick();
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

const stopChat = async () => {
  if (!contextId.value) {
    return;
  }
  await AppApi.stopChat(appId, contextId.value);
};

const closeChat = () => {
  // 关闭聊天逻辑
  globalThis.console.log("关闭聊天");
};

const openHistory = () => {
  showLeft.value = true;
};
</script>

<style scoped>
.knowledge-base {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  align-items: flex-start;
  flex-direction: row;
  margin-bottom: 20px;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f5f5;
}

.message-bubble {
  background-color: #fff;
  border-radius: 8px;
  padding: 8px 12px;
  margin-left: 8px;
  margin-right: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 70%;
  text-align: left;
}

.message-avatar {
  background-color: var(--van-primary-color);
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
}

.message.user .message-bubble {
  background-color: var(--van-primary-color);
  color: white;
}

.message.user .message-bubble span {
  line-height: 1.5;
  white-space: pre-wrap;
  padding: 8px 0;
  display: block;
}

.message.assistant .message-bubble {
  background-color: #fff;
  color: #333;
}

.input-area {
  height: 50px;
  display: flex;
  padding: 8px;
  background-color: #fff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.1);
}

.van-field {
  flex: 1;
  margin-right: 8px;
}

.send-icon {
  width: 24px;
  height: 24px;
}

.send-button {
  border-radius: 10px;
  line-height: 1;
}
</style>
